var that;
class Game {

    constructor(map) {

        this.food = new Food();
        this.snake = new Snake();
        this.map = map;
        that = this;
    }

    startGame() {
        this.food.render(this.map);
        this.food.render(this.map);
        this.food.render(this.map);

        this.snake.render(this.map);

        //让蛇自动运行
        this.snakeRun();
        //控制蛇上下左右运动
        this.bindKeyboard();
        //判断 是否可以吃掉食物
        //判断是否 超出边界
    }

    /**
     * 37--left
     * 38--top
     * 39--right
     * 40--bottom 
     */
    bindKeyboard() {
        document.addEventListener("keydown", (e) => {
            switch (e.keyCode) {
                case 37:
                    that.snake.direction = "left";
                    break;
                case 38:
                    that.snake.direction = "top";
                    break;
                case 39:
                    that.snake.direction = "right";
                    break;
                case 40:
                    that.snake.direction = "bottom";
                    break;

            }
        });
    }

    snakeRun() {
        var timer = setInterval(function() {
            //定时器中会找不到this 需要使用widows 对象
            that.snake.run()
            that.snake.removeNode(that.map);
            that.snake.render(that.map)

            //移动一次就需要判断是否出界
            //获取当前最大宽高
            var maxX = that.map.offsetWidth / that.snake.width;
            var maxY = that.map.offsetHeight / that.snake.height;
            //获取当前蛇头的位置
            var headx = that.snake.body[0].x;
            var heady = that.snake.body[0].y;

            //判断是否与食物重合
            //  var foodx = that.food.x;
            //  var foody = that.food.y;
            var snakeX = headx * that.snake.width;
            var snakey = heady * that.snake.height;

            that.food.element.forEach((element, index) => {

                if (element.offsetLeft === snakeX && element.offsetTop === snakey) {
                    //删除食物
                    that.food.remove(that.map, index);
                    that.food.render(that.map);

                    //自己增加一节
                    var newNode = that.snake.body[that.snake.body.length - 1];
                    that.snake.body.push({
                        x: newNode.x,
                        y: newNode.y,
                        color: newNode.color
                    })
                }
            });



            if (headx < 0 || headx >= maxX || heady < 0 || heady >= maxY) {
                clearInterval(timer);

                alert("Game Over!!");
            }

        }, 150);
    }
}

var map = document.getElementById("map");
var game = new Game(map);
game.startGame();